<template>
  <a-config-provider :theme="antdStyle" :locale="zhCN" :auto-insert-space-in-button="false">
    <router-view />
  </a-config-provider>
</template>

<script setup lang="ts">
  import { useDocumentVisibility, useTitle } from '@vueuse/core'
  import zhCN from 'ant-design-vue/es/locale/zh_CN'
  import { storage } from 'g6-fn'
  import { watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import { personalApi } from '@/services/api'
  import { useUserInfoStore } from '@/store'
  import { useConfigStore } from '@/store/config'
  import { antdStyle } from '@/styles/antd-style'

  import { whiteList } from './router/guard'

  /*TODO:测试用，正式环境删掉---------------------------------------------------------------------------------- */
  const config = useConfigStore()
  useTitle(config.itemType === 'AI中台' ? '第六镜AI中台' : '第六镜人工智能教学实训平台')
  /* ---------------------------------------------------------------------------------- */

  const route = useRoute()
  const router = useRouter()
  const { getMenuData, getUserInfo, $reset, selectAndLink, closeLink } = useUserInfoStore()
  const visibility = useDocumentVisibility()

  /* 初始化用户信息 */
  const initUserInfo = async (cb?: () => void) => {
    const token = storage.get('token')

    /* 无token则不用初始化数据 */
    if (!token) {
      return
    }

    /* 判断token是否有效，token失效则清除token及用户信息 */
    const { data } = await personalApi.verifyToken()
    if (!data) {
      $reset()
      return
    }

    getMenuData()
    getUserInfo()

    cb && cb()
  }

  /* 通过监听窗口显隐来对项目进行初始化链接和页面跳转 */
  watch(visibility, val => {
    /* 窗口隐藏则关闭SSE链接 */
    if (val === 'hidden') {
      closeLink()
      return
    }

    const token = storage.get('token')
    const isWhitePage = whiteList.includes(route.path)
    /* 如果当前页面不在白名单，并且无token，则直接跳转到登录页 */
    if (!isWhitePage && !token) {
      router.replace('/login')
      return
    }

    /* 获取用户信息，并在获取玩信息之后建立SSE链接 */
    initUserInfo(() => {
      console.log('App.vue', route.path)
      if (isWhitePage) {
        return
      }
      selectAndLink(token)
    })
  })

  setTimeout(() => {
    initUserInfo()
  }, 1000)
</script>
